using System;
using System.Collections.Generic;
using System.Drawing;
using SkaldRogueLike.Main.Common;
using SkaldRogueLike.Main.Constants;
using SkaldRogueLike.Main.DungeonGenerating.MapImplementations;

namespace SkaldRogueLike.Main.DungeonGenerating
{
    public class RoomGenerator
    {
        public int MinWidth { get; set; }
        public int MaxWidth { get; set; }
        public int MinHeight { get; set; }
        public int MaxHeight { get; set; }
        public int Count { get; set; }
        
        public RoomGenerator(int minWidth, int maxWidth, int minHeight, int maxHeight, int count)
        {
            MinWidth = minWidth;
            MaxWidth = maxWidth;
            MinHeight = minHeight;
            MaxHeight = maxHeight;
            Count = count;
        }
        
        public DungeonGenerating.MapImplementations.Dungeon PlaceRooms(DungeonGenerating.MapImplementations.Dungeon dungeon)
        {
            var rooms = GenerateRooms(MinWidth, MaxWidth, MinHeight, MaxHeight, Count);
            foreach (var room in rooms)
            {
                int bestPlacementScore = Int16.MaxValue;
                Point? bestPlace = null;
                var cells = dungeon.CorridorCellLocations;
                foreach (var currentPoint in cells)
                {
                    var currentScore = dungeon.GetRoomPlacementScore(currentPoint, room);
                    if (currentScore >= bestPlacementScore) 
                        continue;
                    bestPlacementScore = currentScore;
                    bestPlace = currentPoint;
                }
                if (bestPlace != null) 
                    dungeon.PlaceRoom((Point) bestPlace, room);
            }
            return dungeon;
        }

        private static IEnumerable<Room> GenerateRooms(
            int minWidth, int maxWidth, int minHeight, int maxHeight, int count)
        {
            while (count > 0)
            {
                count--;
                yield return new Room(
                    StaticRandom.Next(minWidth, maxWidth + 1),
                    StaticRandom.Next(minHeight, maxHeight + 1)
                    );
            }
        }
    }
}